document.addEventListener('DOMContentLoaded', () => {
    const videoModal = document.getElementById('video-modal');
    const videoGrid = document.getElementById('video-grid');
    const videoPlayer = document.getElementById('video-player');
    const videoSource = document.getElementById('video-source');
    const closeButton = document.querySelector('.close-button');

    // 获取视频文件列表，包含详细信息
    fetch('/videos')
        .then(response => response.json())
        .then(videos => {
            videos.forEach(video => {
                // 每个视频的详细信息
                const { id, title, category, thumbnailPath, uploader, uploadDate, views } = video;

                const videoElement = document.createElement('div');
                videoElement.classList.add('video');
                videoElement.setAttribute('data-video-id', id);
                videoElement.setAttribute('data-video-src', `/videos/${id}.mp4`);
                
                // 使用模板字符串创建视频卡片，包括视频详细信息
                videoElement.innerHTML = `
                    <img src="${thumbnailPath}" alt="${title}">
                    <h3>${title}</h3>
                    <p>发布人: ${uploader}</p>
                    <p>发布时间: ${new Date(uploadDate).toLocaleDateString()}</p>
                    <p>播放量: ${views}</p>
                    <p>分区: ${category}</p>
                `;
                videoGrid.appendChild(videoElement);
            });
        })
        .catch(error => console.error('加载视频失败:', error));

    // 点击视频时播放
    videoGrid.addEventListener('click', (event) => {
        const video = event.target.closest('.video');
        if (video) {
            const videoSrc = video.getAttribute('data-video-src');
            videoSource.src = videoSrc;
            videoPlayer.load();
            videoModal.style.display = 'block';

            // 发送请求以增加播放量
            const videoId = video.getAttribute('data-video-id');
            fetch(`/video/${videoId}`, { method: 'GET' });
        }
    });

    // 关闭模态框
    closeButton.addEventListener('click', () => {
        videoModal.style.display = 'none';
        videoPlayer.pause();
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === videoModal) {
            videoModal.style.display = 'none';
            videoPlayer.pause();
        }
    });
});

